package com.jzo2o.customer.service.impl;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.api.publics.SmsCodeApi;
import com.jzo2o.common.constants.CommonStatusConstants;
import com.jzo2o.common.constants.ErrorInfo;
import com.jzo2o.common.enums.SmsBussinessTypeEnum;
import com.jzo2o.common.expcetions.BadRequestException;
import com.jzo2o.common.expcetions.CommonException;
import com.jzo2o.common.utils.IdUtils;
import com.jzo2o.common.utils.StringUtils;
import com.jzo2o.customer.config.SecurityConfig;
import com.jzo2o.customer.mapper.RegisterMapper;
import com.jzo2o.customer.model.domain.ServeProvider;
import com.jzo2o.customer.model.dto.request.InstitutionRegisterReqDTO;
import com.jzo2o.customer.service.IRegisterService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Service
@Slf4j
public class RegisterServiceImpl extends ServiceImpl<BaseMapper<ServeProvider>, ServeProvider> implements IRegisterService{


    @Resource
    private SecurityConfig securityConfig;
    @Resource
    private SmsCodeApi smsCodeApi;
    @Resource
    private ServeProviderServiceImpl serveProviderService;

    /**
     * 机构或服务人员注册
     *
     * @param institutionRegisterReqDTO
     */
    @Override
    @Transactional
    public void register(InstitutionRegisterReqDTO institutionRegisterReqDTO) {

        // 数据校验
        if(StringUtils.isEmpty(institutionRegisterReqDTO.getVerifyCode())){
            throw new BadRequestException("验证码错误，请重新获取");
        }

        //远程调用publics服务校验验证码是否正确
        boolean verifyResult = smsCodeApi.verify(institutionRegisterReqDTO.getPhone(), SmsBussinessTypeEnum.INSTITION_REGISTER, institutionRegisterReqDTO.getVerifyCode()).getIsSuccess();
        if(!verifyResult) {
            throw new BadRequestException("验证码错误，请重新获取");
        }



        //校验手机号是否注册
        ServeProvider Phone = lambdaQuery().eq(ServeProvider::getPhone, institutionRegisterReqDTO.getPhone()).one();
        //判断Phone不为空 ，或者已注册 抛出异常 该手机号以被服务人员注册或该账号以被机构注册
        if (Phone != null) {
            throw new BadRequestException("该手机号以被机构注册");
        }




        //给密码进行加密
        institutionRegisterReqDTO.setPassword(securityConfig.passwordEncoder().encode(institutionRegisterReqDTO.getPassword()));



        // 生成唯一的 id

        // 设置机构注册信息
        serveProviderService.add(institutionRegisterReqDTO.getPhone(), 3, institutionRegisterReqDTO.getPassword());












    }
}
